package com.jty.module_user.ui.fragment

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.provider.MediaStore
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.PathUtils
import com.czl.lib_base.config.AppConstants
import com.czl.lib_base.config.AppConstants.Constants.ALBUM_REQUEST_CODE
import com.czl.lib_base.config.AppConstants.Constants.CAMERA_REQUEST_CODE
import com.czl.lib_base.config.AppConstants.Constants.CROP_REQUEST_CODE
import com.jty.lib_base.activity.CameraActivity.CAMERA_RESULT_CODE_101
import com.jty.lib_base.base.BaseFragment
import com.jty.lib_base.data.bean.OssParams
import com.jty.lib_base.event.LiveBusCenter
import com.jty.lib_base.extension.loadDefault
import com.jty.lib_base.extension.loadImage
import com.jty.lib_base.oss.UploadOss
import com.jty.lib_base.utils.WrapContentLinearLayoutManager
import com.jty.lib_base.utils.getCompressPath
import com.jty.lib_base.utils.getLocalAvatarPath
import com.jty.lib_base.widget.SelectPhotoPop
import com.jty.module_user.BR
import com.jty.module_user.R
import com.jty.module_user.adapter.DialogAdapter
import com.jty.module_user.data.DialogData
import com.jty.module_user.databinding.UserFragmentDataBinding
import com.jty.module_user.obj.DialogType
import com.jty.module_user.viewmodel.DataViewModel
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.interfaces.OnBindView
import com.lxj.xpopup.XPopup
import com.orhanobut.logger.Logger
import com.zhihu.matisse.Matisse
import top.zibin.luban.Luban
import top.zibin.luban.OnCompressListener
import java.io.File
import java.io.IOException


@Route(path = AppConstants.Router.User.F_DATA)
class UserDataFragment : BaseFragment<UserFragmentDataBinding, DataViewModel>() {

    lateinit var cropUri: Uri

    override fun initContentView(): Int {
        return R.layout.user_fragment_data
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        val isSupplement = arguments?.getBoolean("isSupplement", false) ?: false
        viewModel.setIsSupplement(isSupplement)
        refreshUI()
        registerUIChangeLiveDataCallBack()
    }


    private fun refreshUI(){
        if (!viewModel.userInfoBean.value?.avatarUrl.isNullOrBlank()){
            val path = getLocalAvatarPath(viewModel.userInfoBean.value?.avatarUrl!!)
            if (File(path).exists()){
                path.let { binding.ivAvatarImg.loadImage(it)}
            }else{
                binding.ivAvatarImg.loadImage(viewModel.userInfoBean.value?.avatarUrl!!.trim())
            }
        }else{
            binding.ivAvatarImg.loadDefault(requireContext().getDrawable(R.drawable.base_man)!!)
        }
    }

    override fun initViewObservable() {
        super.initViewObservable()

        LiveBusCenter.observeModifyPhoneSuccessEventEvent(this) {
            viewModel.modifyPhoneSuccess(it.phone)
        }

        viewModel.uc.showAvatarDialog.observe(this) {
            if (!NetworkUtils.isConnected()){
                showNormalToast("网络已断开，请检查网络")
                return@observe
            }
            XPopup.Builder(requireActivity())
                .enableDrag(true)
                .asCustom(SelectPhotoPop(this))
                .show()
        }
    }

    override fun onBackPressedSupport(): Boolean {
        onBackClick()
        return true
    }


    private fun onBackClick() {
        viewModel.uc.saveUserInfoEvent.call()
    }

    /**
     * 注册viewmodel与view的契约UI回掉事件
     */
    private fun registerUIChangeLiveDataCallBack() {
        viewModel.uc.show4Dialog.observe(this) {
            Logger.e("点击了什么：${it}")
            BottomDialog(
                object : OnBindView<BottomDialog>(R.layout.user_dialog_4, false) {
                    override fun onBind(dialog: BottomDialog?, v: View?) {
                        val tv_title_tag = v?.findViewById<TextView>(R.id.tv_title_tag)
                        val iv_dialog_close = v?.findViewById<ImageView>(R.id.iv_dialog_close)
                        val rv_c = v?.findViewById<RecyclerView>(R.id.rv_c)
                        val btn_ok = v?.findViewById<Button>(R.id.btn_ok)
                        iv_dialog_close?.setOnClickListener(object : View.OnClickListener {
                            override fun onClick(p0: View?) {
                                dialog?.dismiss();
                            }
                        })

                        var dataList = mutableListOf<DialogData>()
                        when (it) {
                            DialogType.PHASE -> {
                                tv_title_tag?.text = "请选择学段"
                                viewModel.sectionList?.let {
                                    for (item1 in viewModel.sectionList!!) {
                                        dataList.add(DialogData(null, item1.id, item1.name, null, null, null, null, null, null))
                                    }
                                }
                            }
                            DialogType.SUBJECT -> {
                                tv_title_tag?.text = "请选择学科"
                                viewModel.subjectList?.let {
                                    for (item1 in viewModel.subjectList!!) {
                                        dataList.add(DialogData(null, item1.id, item1.name, null, null, null, null, null, null))
                                    }
                                }
                            }
                            else -> { // 注意这个块
                                Logger.e("出错了")
                            }
                        }

                        var adapter = DialogAdapter(dataList, it)
                        var mLayoutManager: RecyclerView.LayoutManager =
                            WrapContentLinearLayoutManager(this@UserDataFragment.activity,
                                LinearLayoutManager.VERTICAL,
                                false);
                        rv_c?.layoutManager = mLayoutManager
                        rv_c?.itemAnimator = DefaultItemAnimator()
                        rv_c?.adapter = adapter
                        adapter?.setOnItemClickListener { position, curData ->
                            dialog?.dismiss()
                            if (it == DialogType.PHASE) {
                                viewModel.changeSection(curData!!)
                            } else if (it == DialogType.SUBJECT) {
                                viewModel.changeSubject(curData!!)
                            }
                        }
                        btn_ok?.setOnClickListener { dialog?.dismiss() }
                    }

                }
            ).setAllowInterceptTouch(false)
                .show();
        }

        viewModel.uc.saveUserInfoEvent.observe(this){
            if (viewModel.userInfoUpdate.get()){
                viewModel.modifyUserInfo()
            }else{
                requireActivity().finish()
            }
        }


        viewModel.uc.updateUserInfoSuccess.observe(this){
            requireActivity().finish()
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (CAMERA_REQUEST_CODE == requestCode && CAMERA_RESULT_CODE_101 == resultCode) {
            val path = data!!.getStringExtra("path")
            val uriPath = getImageContentUri(path!!)
            startCropImage(uriPath)
        } else if (ALBUM_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
            val path = Matisse.obtainPathResult(data)[0]
            val uriPath = getImageContentUri(path!!)
            startCropImage(uriPath)
        } else if (CROP_REQUEST_CODE == requestCode && resultCode == RESULT_OK) {
            viewModel.userInfoUpdate.set(true)
            compress(cropUri.path!!)
        }

    }


    /**
     * 上传头像到阿里云
     * isCompress 是否压缩过
     */
    private fun uploadAvatarFile(localPath: String,isCompress:Boolean) {
        var uploadPath = if (isCompress) localPath.substring(localPath.lastIndexOf("/") + 1)
        else "${viewModel.model.getUserId()}_${System.currentTimeMillis()}_avatar.png"
        UploadOss.getInstance()?.upload2OSS(uploadPath, localPath, onUploadListener, null)
    }


    @SuppressLint("Range")
    fun getImageContentUri(filePath: String): Uri {
        val cursor =
            requireActivity().contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                arrayOf(MediaStore.Images.Media._ID),
                MediaStore.Images.Media.DATA + "=?",
                arrayOf(filePath),
                null)
        var uri: Uri? = null
        cursor?.let {
            if (it.moveToFirst()) {
                val id = it.getInt(it.getColumnIndex(MediaStore.MediaColumns._ID))
                val baseUri = Uri.parse("content://media/external/images/media")
                uri = Uri.withAppendedPath(baseUri, "" + id);
            }
            it.close()
        }
        if (uri == null) {
            var values = ContentValues()
            values.put(MediaStore.Images.Media.DATA, filePath)
            uri =
                requireActivity().contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    values)
        }
        return uri!!
    }

    /**
     * 调用系统裁剪功能
     * 进行图片裁剪
     */
    private fun startCropImage(imageUri: Uri) {
        val intent = Intent("com.android.camera.action.CROP")
        val file =
            File(PathUtils.getExternalPicturesPath(), "${viewModel.model.getLoginData()?.id}_avatar.png")
        try {
            if (file.exists()) {
                file.delete()
            }
            file.createNewFile()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        cropUri = Uri.fromFile(file)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(imageUri, "image/*")
        intent.putExtra("crop", true)
        intent.putExtra("return-data", false)   //这里不能设置为true, 为true时华为设备无法裁剪
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString()) //设置输出格式，有效减小图片大小
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropUri)
        startActivityForResult(intent, CROP_REQUEST_CODE) //启动裁剪程序
    }


    /**
     * 压缩图片
     */
    private fun compress(path: String) {
        Logger.i("m1 compress start${path}")
        //如果文件大小本身小于100，不压缩
        var leastCompressSize = 100
        if (File(path).length() < (leastCompressSize shl 10)){
            uploadAvatarFile(path,false)
            return
        }
        //图片过大则进行压缩
        Luban.with(requireContext()).load(path)
            .ignoreBy(100)
            .setTargetDir(getCompressPath( "avatar"))
            .setRenameListener { "${viewModel.model.getUserId()}_${System.currentTimeMillis()}_avatar.png" }
            .setCompressListener(object : OnCompressListener {
                override fun onStart() {

                }
                override fun onSuccess(file: File?) {
                    Logger.i("m1 compress onSuccess${file?.absolutePath.toString()}")
                    uploadAvatarFile(file?.absolutePath.toString(),true)
                }

                override fun onError(e: Throwable?) {

                }

            }).launch()
    }

    private val onUploadListener = object : UploadOss.OnUploadListener {
        override fun uploadSuccess(
            uploadFile: String?,
            localFile: String,
            ossParams: OssParams?,
        ): String? {
            viewModel.userInfoBean.value?.avatarUrl = uploadFile!!
            viewModel.userInfoBean.postValue(viewModel.userInfoBean.value)
            var userInfoData = viewModel.model.getUserInfoData()
            userInfoData?.avatarUrl = uploadFile
            viewModel.model.saveUserInfoData(userInfoData!!)
            refreshUI()
            return null
        }

        override fun uploadFail(
            uploadFile: String?,
            localFile: String,
            ossParams: OssParams?,
        ): String? {
            return null
        }

    }
}